<!--
 *Author：jxx
 *Date：{Date}
 *Contact：283591387@qq.com
 *业务请在@/extension/mes/mes/ProductPlan.jsx或ProductPlan.vue文件编写
 *新版本支持vue或【表.jsx]文件编写业务,文档见:https://doc.volcore.xyz/docs/view-grid、https://doc.volcore.xyz/docs/web
 -->
<template>
    <div class="grid">
        <view-grid ref="grid" :columns="columns" :detail="detail" :details="details" :editFormFields="editFormFields"
            :editFormOptions="editFormOptions" :searchFormFields="searchFormFields"
            :searchFormOptions="searchFormOptions" :table="table" :extend="extend" :onInit="onInit" :onInited="onInited"
            :searchBefore="searchBefore" :searchAfter="searchAfter" :addBefore="addBefore" :updateBefore="updateBefore"
            :delBefore="delBefore" :delAfter="delAfter" :auditModelOpenBefore="auditModelOpenBefore"
            :rowClick="rowClick" :modelOpenBefore="modelOpenBefore" :modelOpenAfter="modelOpenAfter"
            :detailSortEnd="detailSortEnd">
            <!-- 自定义组件数据槽扩展，更多数据槽slot见文档 -->
            <template #gridHeader>
            </template>
            <template #gridFooter>
                <div class="productPlanDetail">
                    <productPlanDetail ref="productPlanDetailRef"></productPlanDetail>
                </div>
            </template>
            <template #modelBody>
                <el-alert style="margin-bottom: -1px" title="可拖动明细表对【序号】自动完成排序" class="alert-primary"
                    :closable="false"></el-alert>
            </template>
        </view-grid>
    </div>
    <select-material ref="materialRef" @onSelectMaterial="onSelectMaterial"></select-material>
    <select-materialBom ref="materialBomRef" @onSelectMaterialBom="onSelectMaterialBom"></select-materialBom>
    <select-technologicalProcess ref="technologicalProcessRef"
        @onSelectTechnologicalProcess="onSelectTechnologicalProcess"></select-technologicalProcess>
    <select-saleOrder ref="productPlanOrderRef" @onSelectSaleOrder="onSelectSaleOrder"></select-saleOrder>
</template>
<script setup lang="jsx">
import productPlanDetail from './ProductPlanDetail.vue'
import extend from "@/extension/mes/mes/ProductPlan.jsx";
import viewOptions from './ProductPlan/options.js'
import SelectMaterial from './ProductPlanSelectMaterial.vue'
import SelectMaterialBom from './ProductPlanSelectMaterialBom.vue'
import SelectTechnologicalProcess from './ProductPlanSelectTechnologicalProcess.vue'
import SelectSaleOrder from './ProductPlanSelectOrder.vue'
import { ref, reactive, getCurrentInstance, watch, onMounted } from "vue";
const grid = ref(null);
const { proxy } = getCurrentInstance()
//http请求，proxy.http.post/get
const { table, editFormFields, editFormOptions, searchFormFields, searchFormOptions, columns, detail, details } = reactive(viewOptions())
const materialRef = ref();
const materialBomRef = ref();
const technologicalProcessRef = ref();
const productPlanDetailRef = ref();
const productPlanOrderRef = ref();
const loted = ref(false);
let gridRef;//对应[表.jsx]文件中this.使用方式一样
//生成对象属性初始化
const onInit = async ($vm) => {
    gridRef = $vm;
    //与jsx中的this.xx使用一样，只需将this.xx改为gridRef.xx
    //更多属性见：https://doc.volcore.xyz/docs/view-grid
    //缓存主表方法，返回主表选中的行，在下面的bom明细表[MES_Bom_Detail]中会调用
    proxy.base.setItem('getPlanSelectRow', () => {
        return gridRef.getTable(true).getSelected();
    })
    proxy.base.setItem('mainSearch', () => {
        gridRef.search()
    })
    //设置弹出框编辑宽度
    // gridRef.boxOptions.width = 1100
    //启用明细表排序
    gridRef.detailOptions.sortable = true

    gridRef.detailOptions.pagination.sortName = "MaterialNo";  //明细表排序字字段
    gridRef.detailOptions.pagination.order = "asc"; //明细表排序方式desc或者asc


}
//生成对象属性初始化后,操作明细表配置用到
const onInited = async () => {
    columns.forEach(x => {
        //开启表头过滤
        x.filterData = true;
    })
    
    gridRef.height = gridRef.height - 310;
    if (gridRef.height < 200) {
        gridRef.height = 200;
    }
    gridRef.buttons.splice(1, 0, {
        name: '选择销售订单', //按钮名称
        icon: 'el-icon-document', //按钮图标:组件示例->图标
        //primary、success、warning、error、info、text、danger
        type: 'primary',
        plain: true,
        onClick: () => {
            productPlanOrderRef.value.open()
        }
    })
    //选择Bom
    const bomNoCol = gridRef.detailOptions.columns.find((x) => {
        return x.field == 'BomNo'
    })
    bomNoCol.render = (h, { row, column, index }) => {

        return (
            <div>
                <el-button
                    link
                    onClick={($e) => {
                        if (row.MaterialId == null || row.MaterialId == undefined) {
                            return proxy.$message.error("请选择物料！");
                        }
                        materialBomRef.value.open(row)
                    }}
                    class="el-icon-search"
                    style="color: #2196F3;cursor: pointer;"
                ></el-button>

                <span style="margin-right:5px">{row.BomNo}</span>
            </div>
        )

    }
    //选择工艺
    const technolpgicalProcessCol = gridRef.detailOptions.columns.find((x) => {
        return x.field == 'TechnologicalProcessNo'
    })
    technolpgicalProcessCol.render = (h, { row, column, index }) => {

        return (
            <div>
                <el-button
                    link
                    onClick={($e) => {
                        if (row.MaterialId == null || row.MaterialId == undefined) {
                            return proxy.$message.error("请选择物料！");
                        }
                        technologicalProcessRef.value.open(row)
                    }}
                    class="el-icon-search"
                    style="color: #2196F3;cursor: pointer;"
                ></el-button>

                <span style="margin-right:5px">{row.TechnologicalProcessNo}</span>
            </div>
        )

    }


    //选择物料
    const materialNoCol = gridRef.detailOptions.columns.find((x) => {
        return x.field == 'MaterialNo'
    })
    materialNoCol.render = (h, { row, column, index }) => {

        return (
            <div>
                <el-button
                    link
                    onClick={($e) => {
                        materialRef.value.open(row, index)
                    }}
                    class="el-icon-search"
                    style="color: #2196F3;cursor: pointer;"
                ></el-button>

                <span style="margin-right:5px">{row.MaterialNo}</span>
            </div>
        )

    }

    // 根据单价数量计算金额
    gridRef.detailOptions.columns.forEach((col) => {
        //给数量Qty字段合计自定义显示格式、同时与表单联动显示
        if (col.field == 'AllAmount') {
            //将eidt设置为null不开启编辑
            col.edit = null;
            col.formatter = (row) => {

                return (row.AllPrice || 0) * (row.PlanQty || 0)
            }
        }
    });

    detail.columns.forEach(c => {
        if (c.field == 'LotText') {
            c.checkEdit = (row, column, index) => {
                return row.IsLoted == 1

            }
        }

    })

    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'MaterialId') {
            //将eidt设置为null不开启编辑
            x.edit = null;
            initLotSelectTable()
        }
    })
    gridRef.detailOptions.columns.forEach(x => {
        if (x.field == 'PlanQty') {
            x.min = 0
        }
    })

}
const initLotSelectTable = () => {

    gridRef.detailOptions.columns.forEach((item) => {
        if (item.field == 'LotText') {
            item.edit = { type: "selectTable" }
            item.readonly = false;

            item.url = 'api/LotMasterDetail/search';

            //输入框只读操作，需要将columns的search字段设置为true，否则无法过滤数据
            //item.inputReadonly=true;
            //设置显示的字段
            item.columns = [
                { field: 'LotMasterDetailId', title: '批号明细标识', type: 'string', width: 120, hidden: true },
                { field: 'LotText', title: '批号', type: 'string', width: 100, search: true },
            ];

            //选中table数据后，回写到表单
            //editRow:当前正在编辑的行
            //rows:选中的行
            item.onSelect = (editRow, rows) => {
                editRow.LotMasterDetailId = rows[0].LotMasterDetailId;
                editRow.LotText = rows[0].LotText;
            };

            //(输入框搜索)表格数据加载前处理
            //editRow:当前正在编辑的行
            //param:请求的参数
            item.loadBefore = (editRow, param, callback) => {

                param.value = editRow.MaterialId;
                callback(true);
            };

            //表格数据加载后处理
            //editRow:当前正在编辑的行
            //rows:后台返回的数据
            item.loadAfter = (editRow, rows, callback, result) => {
                callback(true);
            };

            /****下面的这些都是可以选配置，上面的是必填的******/
            //监听输入框变动与回车事件
            item.onKeyPress = (val, $event, row) => {
                console.log(val);
                if ($event.keyCode == 13) {
                    console.log('按了回车');
                }
                //清空值时给其他字段设置值
                // if(!val&&value+''!='0'){
                //     row.xx=null;
                // }
            }
            //设置弹出框高度(默认200)
            item.height = 200;
            //设置弹出框宽度(默认500)
            item.selectWidth = 500;
            item.textInline = true; //设置表格超出显示...
            //设置表格是否单选
            item.single = true;
            //隐藏分页
            item.paginationHide = true;
            //设置默认分页大小与分页信息
            item.pagination = { size: 30, sizes: [30, 60, 90] };
        }
    });
}
const searchBefore = async (param) => {
    //界面查询前,可以给param.wheres添加查询参数
    //返回false，则不会执行查询
    return true;
}
const searchAfter = async (rows, result) => {
    return true;
}
const addBefore = async (formData) => {
    //新建保存前formData为对象，包括明细表，可以给给表单设置值，自己输出看formData的值
    return true;
}
const updateBefore = async (formData) => {
    //编辑保存前formData为对象，包括明细表、删除行的Id
    return true;
}
const delBefore = (ids, rows) => { //查询界面的表删除前 ids为删除的id数组,rows删除的行
    let isDeleted = true
    rows.forEach(row => {
        if (row.AuditStatus == 1) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已审核不允许删除！");
            return isDeleted;
        }
        if (row.IsCreateTask == 2) {
            isDeleted = false
            proxy.$message.error(row.BillNo + "已创建生产任务！");
            return isDeleted
        }
    });
    return isDeleted;//返回false，界面上不会显示
}
const delAfter = (res, rows) => { //查询界面的表删除后方法
    productPlanDetailRef.value.$refs.grid.search();

    return true;
}
const auditModelOpenBefore = (rows, isAnit) => {//审核前
    //rows:审批选中的行数据
    let selectRows = gridRef.getSelectRows()
    let flag = false
    if (isAnit) {
        selectRows.forEach(row => {
            if (row.IsCreateTask != 1) {
                return proxy.$message.error(row.BillNo + "已创建生产任务！");
            }
            else {
                flag = true;
            }
        });
    }
    else {
        flag = true;
    }

    // rows.forEach(row => {
    //     if (row.AuditStatus != 0) {

    //     }
    // });
    //打开审批弹出框时可以调用后台接口做一些处理
    // var _result = await this.http.post("/api/表/xxx", {}, true).then(result => {
    //     console.log("1、异步请求前")
    //     return result;
    // })
    // if(_result){

    // }
    //返回不会打开审批弹出框
    return flag;
}

const rowClick = ({ row, column, event }) => {
    //查询界面点击行事件
    // grid.value.toggleRowSelection(row); //单击行时选中当前行;
    //点击行清除选中的行(用于下面明细表判断)
    grid.value.clearSelection();
    //点击行默认选中
    grid.value.toggleRowSelection(row); //单击行时选中当前行;
    //加载明细表
    productPlanDetailRef.value.$refs.grid.search();
}
const modelOpenBefore = async (row) => {//弹出框打开后方法
    return true;//返回false，不会打开弹出框
}
const modelOpenAfter = (row, currentAction, isCopyClick) => {
    //弹出框打开后方法,设置表单默认值,按钮操作等


    gridRef.setFormReadonly(false);

    if (gridRef.currentAction == 'Add') {
        gridRef.editFormFields.BillDate = proxy.base.getDate();
        gridRef.editFormFields.IsCreateTask = 1;
        gridRef.editFormFields.BillTypeId = 1;
        gridRef.boxButtons.forEach((btn) => {
            if (btn.name == '保存') {
                btn.hidden = false;
                //或者设置只读
                // btn.readonly = true;
            }

        });
    }
    else {
        if (row.AuditStatus != 0) {
            gridRef.setFormReadonly(true);
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = true;
                    //或者设置只读
                    // btn.readonly = true;
                }

            });
        }
        else {
            gridRef.boxButtons.forEach((btn) => {
                if (btn.name == '保存') {
                    btn.hidden = false;
                    //或者设置只读
                    // btn.readonly = true;
                }
            });

        }
    }
}
const onSelectSaleOrder = (row) => {
    console.log(row)
    setTimeout(() => {

        gridRef.editFormFields.BillDate = proxy.base.getDate()
        gridRef.editFormFields.BillTypeId = 2
        gridRef.editFormFields.DepartmentId = row.departmentId
        gridRef.editFormFields.CustomerId = row.customerId
        gridRef.editFormFields.IsCreateTask = row.isCreateTask
        gridRef.editFormFields.ExternalDataId = row.externalDataId

        let productPlanDetails = row.productPlanDetail
        productPlanDetails.forEach(detailRow => {
            gridRef.getTable("ProductPlanDetail").addRow({
                MaterialId: detailRow.materialId,
                MaterialNo: detailRow.materialNo,
                MaterialName: detailRow.materialName,
                Spec: detailRow.spec,
                MaterialTypeId: detailRow.materialTypeId,
                UnitId: detailRow.unitId,
                IsLoted: detailRow.isLoted,
                LotText: detailRow.lotText,
                PlanQty: detailRow.planQty,
                AllPrice: detailRow.allPrice,
                BomId: detailRow.bomId,
                BomNo: detailRow.bomNo,
                TechnologicalProcessId: detailRow.technologicalProcessId,
                TechnologicalProcessNo: detailRow.technologicalProcessNo,
            })
        })


    }, 400)


    gridRef.add()
}



const detailSortEnd = (rows, newIndex, oldIndex, table) => {
    rows.forEach((x, index) => {
        x.Sequence = index + 1
    })
}
//监听表单输入，做实时计算
//watch(() => editFormFields.字段,(newValue, oldValue) => {	})
//对外暴露数据
defineExpose({})
</script>
<style lang="less" scoped>
.productPlanDetail {
    margin-top: 13px;
    border-top: 7px solid #eee;
}
</style>
